﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Sockets;

namespace NetworkLibrary
{
    public class Buffer
    {
        private int _length;
        private int _size;
        private int _index;
        private byte[] _buffer;
        ConcurrentStack<int> _indexs;
        public Buffer(int bufferSize, int bufferCount)
        {
            _index = 0;
            _length = bufferSize * bufferCount;
            _size = bufferSize;
            _indexs = new ConcurrentStack<int>();
            _buffer = new byte[_length];
        }
        public bool SetBuffer(SocketAsyncEventArgs eventArgs)
        {
            if (_indexs.TryPop(out var index))
            {
                eventArgs.SetBuffer(_buffer, index, _size);
                return true;
            }
            if (_index + _size <= _length)
            {
                eventArgs.SetBuffer(_buffer, _index, _size);
                _index += _size;
                return true;
            }
            return false;
        }
        public void FreeBuffer(SocketAsyncEventArgs eventArgs)
        {
            _indexs.Push(eventArgs.Offset);
            eventArgs.SetBuffer(null, 0, 0);
        }
    }
}